<template>
	<view class="container bg-main pos-r">
		
		<view class="padding-xl dflex-c dflex-flow-c">
			<view class="headimg-box margin-top margin-bottom-xl">
				<image class="headimg border-radius-c" :src="(member && member.member_headimg) || '/static/images/user/default.png'"></image>
			</view>
			
			<swiper class="w-full" duration="200" disable-touch style="height: 190rpx !important;" :current="loginWay == 'code' ? 0 : 1">
				<!-- 验证码登录 -->
				<swiper-item>
					<view class="w-full dflex padding-bottom-sm">
						<view class="iconfont iconshouji margin-right"></view>
						<view class="flex1 dflex">
							<input class="border-line padding-sm flex1" type="number" data-key="mobile" maxlength="11" :value="state.mobile" @input="inputChange" placeholder="请输入手机号" />
							<!-- <view v-if="0 == 1" class="padding-tb-sm ft-dark" @click="send_code">获取</view> -->
						</view>
					</view>
					<!-- #ifdef MP-WEIXIN -->
					<use-smscode type="login" :mobile="state.mobile" @change="codeChange" @confirm="tologin"></use-smscode>
					<!-- #endif -->
					
					<!-- #ifndef MP-WEIXIN -->
					<use-smscode type="login" :mobile="state.mobile" :agreement="agreement" :agreementContent="agreementContent" @change="codeChange" @confirm="tologin"></use-smscode>
					<!-- #endif -->
				</swiper-item>
				
				<!-- 账号密码登录 -->
				<swiper-item>
					<view class="w-full dflex padding-bottom-sm">
						<view class="iconfont iconshouji margin-right"></view>
						<view class="flex1 dflex">
							<input class="border-line padding-sm flex1" type="number" data-key="mobile" maxlength="11" :value="state.mobile" @input="inputChange" placeholder="请输入手机号" />
								<!-- <view v-if="0 == 1" class="padding-tb-sm ft-dark" @click="send_code">获取</view> -->
						</view>
					</view>
					
					<view class="w-full dflex">
						<view class="iconfont iconmima margin-right"></view>
						
						<view class="dflex flex1 border-line">
							<!-- #ifdef MP -->
							<input class="padding-sm flex1" type="text" password data-key="password" maxlength="20"
								:value="state.password" @input="inputChange" @confirm="tologin" placeholder="请输入密码" />
							<!-- #endif -->
							
							<!-- #ifndef MP -->
							<input class="padding-sm flex1" type="password" password data-key="password" maxlength="20"
								:value="state.password" @input="inputChange" @confirm="tologin" placeholder="请输入密码" />
							<!-- #endif -->
							
							<view class="pos-r">
								<view class="vertical-line" style="right: calc(100% + 20rpx);"></view>
								<view class="padding-tb-sm ft-dark" @click="toforget">忘记密码</view>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
			
			<view class="w-full margin-top-xxl">
				<view class="dflex-b border-radius-lg">
					<view class="tac padding-tb-sm flex1 bg-base fs" @click="tologin">登录</view>
				</view>
				<!-- 正式上线取消，测试账号仅做为测试使用 -->
				<view class="dflex-b border-radius-lg margin-top">
					<view class="tac padding-tb-sm flex1 bg-drak fs" @click="toTestLogin">测试账号登录</view>
				</view>
			</view>
			
			<view class="dflex-b w-full margin-bottom-sm ft-dark-4">
				<view v-if="loginWay == 'pwd'" class="padding-tb-sm" @click="loginWayChange('code')">验证码登录</view>
				<view v-if="loginWay == 'code'" class="padding-tb-sm" @click="loginWayChange('pwd')">账号密码登录</view>
				<!-- <view class="padding-tb-sm" @click="toregister">立即注册</view> -->
			</view>
			<!-- #ifndef MP-WEIXIN -->
			<view v-if="agreementDatas && agreementDatas.length > 0" class="dflex w-full margin-top" @click="toAgreement">
				<view v-if="agreement" class="iconfont iconxuanzhongzhuangtai margin-right-xs ft-base"></view>
				<view v-else class="iconfont iconweixuanzhongzhuangtai margin-right-xs"></view>
				<view class="ft-dark-3">
					已阅读并同意<text v-for="(item, idx) in agreementDatas" :key="idx" class="ft-base" @click.stop="toContent(item)">《{{item.name}}》</text>
				</view>
			</view>
			<!-- #endif -->
		</view>
		
		
	</view>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
	import { useStore } from 'vuex'
	import { useRouter } from 'vue-router'
	import { onShow } from '@dcloudio/uni-app'
	import { useMutations } from 'vuex-composition-helpers'
		
	const { proxy } = getCurrentInstance()
	const { login, logout, token } = useMutations(['login', 'logout', 'token'])
		
	const store = useStore()
	const router = useRouter()
	
	const loginWay = ref('code')
	const agreement = ref(true) // 待修改
	const agreementContent = ref('请阅读并同意')
	
	const code = ref('')
	const agreementDatas = ref([])
	const authorize = ref(0)
	const bindMobileShow = ref(false)
	const privacyShow = ref(false)
	const agreeToLogin = ref(0)
	
	const state = reactive({
		mobile: '',
		password: ''
	})
	
	const member = computed(() => store.state.member)
	const config = computed(() => proxy.config)
	const islogin = computed(() => store.state.islogin)
		
	const loginWayChange = (res) => {
		loginWay.value = res
	}
	
	const codeChange = (code) => {
		code.value = code
	}
	
	const toAgreement = () => {
		agreement.value = !agreement.value
	}
	
	const inputChange = (e) => {
	  const key = e.currentTarget.dataset.key
	  state[key] = e.detail.value
	}
	
	const toforget = () => {
		// 忘记密码
		uni.navigateTo({
			url: '/pages/login/forgot-password'
		})
	}
	
	const toregister = () => {
		// 注册页
		uni.navigateTo({
			url: '/pages/login/register'
		})
	}
	
	// 测试账号登录
	const toTestLogin = () => {
		loginWay.value = 'pwd'
		
		state.mobile = '18961147327'
		state.password = '1234'
		
		tologin()
	}
	
	const tologin = async (type) => {
		// if (islogin.value) return
		// if (is_login.value) return
	
		if (!state.mobile) {
			proxy.$api.msg('请输入手机号')
			return
		}
		
		let url = 'member/login'
		let data = {
			sharemid: uni.getStorageSync('__use_share_mid') || ''
		}
		// 密码登录
		if (loginWay.value == 'pwd') {
			if (!state.password) {
				proxy.$api.msg('请输入密码')
				return
			}
			if (proxy.$api.trim(state.password).length < 4) {
				proxy.$api.msg('密码长度不能小于4位')
				return
			}
			
			data.username = state.mobile
			data.password = state.password
		// 验证码登录
		} else if (loginWay.value == 'code') {
			if (!code.value) {
				proxy.$api.msg('请输入验证码');
				return;
			}
			if (code.value.length != 6) {
				proxy.$api.msg('验证码错误');
				return;
			}
			
			url = 'member/loginBySms';
			data.mobile = state.mobile;
			data.code = code.value
			// #ifdef APP || MP-WEIXIN
			if (bindMobileShow.value) {
				// #ifdef APP
				if (!hasWeixinAuth.value) {
					proxy.$api.msg('应用未启用微信授权登录')
					return
				}
				// #endif
				data.wxcode = await getWeixinCode()
				
				// #ifdef MP-WEIXIN
				data.user = uni.getStorageSync('__wxuser') || {}
				data.from = 'mp'
				// #endif
				
				// #ifdef APP
				data.from = 'app'
				// #endif
				
				// 解绑并绑定
				if (type == 'unbind-bind') data.type = type
			}
			// #endif
		}
		
		// #ifdef MP-WEIXIN
		if (!agreement.value) {
			privacyShow.value = true
			agreeToLogin.value = 2
			return
		}
		// #endif
		
		// #ifndef MP-WEIXIN
		if (!agreement.value) {
			proxy.$api.msg(agreementContent.value)
			return
		}
		// #endif
		
		uni.showLoading({
			title: '登录中'
		})
	
		proxy.$func.usemall
			.call(url, data)
			.then(res => {
				uni.hideLoading();
				
				if (res.code == 100) {
					// 当前手机号已绑定其他微信号，弹窗询问是否解绑
					uni.showModal({
						content: '已绑定其他微信号，是否解绑并绑定当前微信号',
						cancelText: '取消',
						confirmText: '解绑并绑定',
						success: (res) => {
							if (res.confirm) {
								// 登录类型解绑并绑定
								tologin('unbind-bind');
							}
						}
					})
					return;
				}
				
				if (res.code == 200) {
					// 调用 store login
					if (res.datas.member && res.datas.member.is_plus === '付费会员' && res.datas.member.plus_time >= new Date().getTime()) {
						res.datas.member.vip = true;
					}
					uni.setStorage({
						key: '__mobile',
						data: state.mobile
					})
					uni.setStorage({
						key: '__loginWay',
						data: state.loginWay
					})
					login(res.datas)
					
					console.log('login login login')
	
					proxy.$api.msg('登录成功')
					proxy.$api.back()
					return
				}
	
				proxy.$api.msg(res.msg)
			})
	}

	const getWeixinCode = async () => {
		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN
			uni.login({
				success: (res) => {
					resolve(res.code)
				},
				fail: (err) => {
					reject(err)
				}
			});
			// #endif
			// #ifdef APP
			weixinAuthService.authorize((res) => {
				resolve(res.code)
			}, (err) => {
				console.log(err)
				reject(new Error('微信登录失败'))
			})
			// #endif
		})
	}
	
	onShow(() => {
	  console.log('login Show')
	  
	  // #ifdef MP-WEIXIN
	  if (uni.canIUse('getPrivacySetting')) {
	  	uni.getPrivacySetting({
	  			console.log('getPrivacySetting', res)
	  			this.agreement = true;
	  			if (res.needAuthorization) {
	  				agreement.value = false;
	  				privacyShow.value = true;
	  				agreeToLogin.value = 0
	  			}
	  		},
	  		fail: err => {
	  			console.log('getPrivacySetting err', err)
	  		}
	  	});
	  } else {
	  	agreement.value = true;
	  }
	  // #endif
	  
	  uni.getStorage({
	  	key: '__mobile',
	  	success: (res) => {
	  		state.mobile = res.data || ''
	  	}
	  });
	  
	  uni.getStorage({
	  	key: '__loginWay',
	  	success: (res) => {
	  		loginWay.proxy = res.data || 'code'
	  	}
	  })
	  
	  // #ifndef APP || H5
	  // 查看用户是否已授权获取用户数据
	  if (uni.canIUse('getSetting')) {
	  	uni.getSetting({
	  		success: (res) => {
	  			console.log('getSetting ', res)
	  			authorize.value = res.authSetting['scope.userInfo']
	  			console.log('getSetting scope.userInfo authorize ', authorize.value)
	  		}
	  	});
	  }
	  // #endif
	})
</script>

<style lang="scss">
	.headimg-box {
		image {
			width: 130rpx;
			height: 130rpx;
		}
	}
	
	.login-area {
		view { width: 25vw; }
	}
	
	.bind-area {
		width: 100vw;
		padding: 80rpx;
		padding-top: 100rpx;
	
		.field {
			background-color: #f5f5f5;
			textarea {
				height: 100rpx !important;
			}
		}
	}
</style>